<!--
 * @Description:
 * @Author: 月间
 * @Date: 2024-10-27 23:36:05
 * @LastEditTime: 2025-01-09 22:04:18
 * @LastEditors:
-->
<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { useBoolean } from '@sa/hooks';
import { fetchAddPost, fetchUpdatePost } from '@/service/api';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { enableStatusOptions } from '@/constants/business';

defineOptions({
  name: 'PostOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.Post | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增岗位',
    edit: '编辑岗位'
  };
  return titles[props.operateType];
});

type Model = Api.SystemManage.PostUpdate;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: null,
    postCode: '',
    postName: '',
    remark: '',
    status: null,
    postSort: 0
  };
}
// 移除id和remark
type RuleKey = Extract<keyof Model, 'postCode' | 'postName' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  postCode: defaultRequiredRule,
  postName: defaultRequiredRule,
  status: defaultRequiredRule
};

const roleId = computed(() => props.rowData?.id || -1);

const isEdit = computed(() => props.operateType === 'edit');

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  let res = null;
  // request
  if (props.operateType === 'edit') {
    res = await fetchUpdatePost(model);
  } else {
    res = await fetchAddPost(model);
  }
  const { error, data } = res;
  if (error) {
    return;
  }
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="岗位名称" path="postName">
          <NInput v-model:value="model.postName" placeholder="岗位名称" />
        </NFormItem>
        <NFormItem label="岗位编码" path="postCode">
          <NInput v-model:value="model.postCode" placeholder="岗位编码" />
        </NFormItem>
        <NFormItem label="岗位状态" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
        <NFormItem label="岗位顺序" path="postSort">
          <NInput v-model:value="model.postSort" placeholder="岗位顺序" />
        </NFormItem>
        <NFormItem label="岗位描述" path="remark">
          <NInput v-model:value="model.remark" placeholder="岗位描述" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
